package linuxbox.filelib.servlet;

import javax.servlet.http.*;
import java.sql.*;

import org.apache.log4j.Logger;

import linuxbox.BoxStatic;
import linuxbox.common.Action;
import linuxbox.common.BoxSession;
import linuxbox.filelib.logic.FileLibHome;
import linuxbox.filelib.logic.FileLibEntry;
import linuxbox.exception.LinuxboxException;
/**
 * <p>Title: </p>
 * <p>Description: </p>
 * <p>Copyright: Copyright (c) 2002</p>
 * <p>Company: </p>
 * @author unascribed
 * @version 1.0
 */

public class EditFolderAction extends Action
{
  protected static String folderEditJSP = null;
  protected static String folderViewJSP = null; //folder attributes
  protected static String folderContentJSP = null;
  protected static String folderDeleteJSP = null;

  protected static FileLibHome home = FileLibHome.getInstance();
  protected static Logger logger = Logger.getLogger(EditFolderAction.class.getName());

  public void doAction(HttpSession session, BoxSession aBoxSession,
  HttpServletRequest req, HttpServletResponse resp) throws Exception
  {
    String str = req.getParameter("SubmitAdd");
    FileLibEntry entry = null;
    if ( str != null )
    {
      String tmp = (String) session.getAttribute("filelib.CURFOLDER");
      int parentID = home.ROOT;
      if (tmp != null && tmp.length() > 0)
        parentID = Integer.parseInt(tmp);
      FileLibEntry parent = home.get(parentID);
      if (parent == null)
      {
        sendFile(BoxStatic.errorJSP,req,resp);
        return;
      }

      if (!home.checkAccessRights(aBoxSession.getID(), parent, home.WRITE_ALLOW))
      {
        logger.warn("Access rights violation for user " + aBoxSession.getLoginID() + " " + parent.getName());
        sendFile(BoxStatic.accessRightErrorJSP,req,resp);
        return;
      }
      entry = new FileLibEntry();
      entry.setParent(parentID);
      entry.setId(-1);
      entry.setIsfolder(true);
      entry.setOwnerid(aBoxSession.getID());
      entry.setCreatetime(new Timestamp(System.currentTimeMillis()));
      entry.setLastmodifiedtime(new Timestamp(System.currentTimeMillis()));
      entry.setAttributes(home.INHERIT);

      session.setAttribute("filelib.CURENTRY", entry); //new folder
      sendFile(folderEditJSP,req,resp);
      return;
    }

    str = req.getParameter("SubmitCancel");
    if ( str != null )
    {
      entry = (FileLibEntry)session.getAttribute("filelib.CURENTRY");
      if (entry == null)
      {
        logger.error("No entry found");
        sendError("No entry found", req, resp);
        return;
      }
      sendFile(folderContentJSP, req, resp);
      return;
    }

    str = req.getParameter("SubmitEdit");
    if ( str != null )
    {
      String tmp = (String) session.getAttribute("filelib.CURFOLDER");
      int ID = home.ROOT;
      if (tmp != null && tmp.length() > 0)
        ID = Integer.parseInt(tmp);
      entry = home.get(ID);
      if (entry == null)
      {
        entry = (FileLibEntry) session.getAttribute("filelib.CURENTRY");
      }
      if (entry == null)
      {
        sendError(new LinuxboxException("Folder not exist!"), req, resp);
        return;
      }

      if (!home.checkAccessRights(aBoxSession.getID(), entry, home.WRITE_ALLOW))
      {
        logger.warn("Access rights violation for user " + aBoxSession.getLoginID() + " " + entry.getName());
        sendFile(BoxStatic.accessRightErrorJSP,req,resp);
        return;
      }

      session.setAttribute("filelib.CURENTRY", entry);
      sendFile(folderEditJSP,req,resp);
      return;
    }

    str = req.getParameter("SubmitView");
    if ( str != null )
    {
      String tmp = (String) session.getAttribute("filelib.CURFOLDER");
      int ID = home.ROOT;
      if (tmp != null && tmp.length() > 0)
        ID = Integer.parseInt(tmp);
      entry = home.get(ID);
      if (entry == null)
      {
        sendFile(BoxStatic.errorJSP,req,resp);
        return;
      }
      viewFolder(entry, session, aBoxSession, req, resp);
      return;
    }

    str = req.getParameter("SubmitSave");
    if ( str != null )
    {
      if (saveFolder(session, aBoxSession, req, resp))
      {
        sendFile(folderContentJSP, req, resp);
      }
      return;
    }

    str = req.getParameter("SubmitAskDelete");
    if ( str != null )
    {
      String tmp = (String) req.getParameter("ID");
      int ID = -1;
      if (tmp != null && tmp.length() > 0)
        ID = Integer.parseInt(tmp);
      if (ID > 0)
      {
        entry = home.get(ID);
        if (entry == null)
        {
          sendFile(BoxStatic.errorJSP,req,resp);
          return;
        }

        if (!home.checkAccessRights(aBoxSession.getID(), entry, home.WRITE_ALLOW))
        {
          logger.warn("Access rights violation for user " + aBoxSession.getLoginID() + " " + entry.getName());
          sendFile(BoxStatic.accessRightErrorJSP,req,resp);
          return;
        }
      }
      else
      {
        sendFile(folderContentJSP, req, resp);
        return;
      }

      session.setAttribute("filelib.CURENTRY", entry);
      sendFile(folderDeleteJSP,req,resp);
      return;
    }

    str = req.getParameter("SubmitDelete");
    if ( str != null )
    {
      entry = (FileLibEntry)session.getAttribute("filelib.CURENTRY");
      if (entry == null)
      {
        sendFile(BoxStatic.errorJSP,req,resp);
        return;
      }

      if (!home.checkAccessRights(aBoxSession.getID(), entry, home.WRITE_ALLOW))
      {
        logger.warn("Access rights violation for user " + aBoxSession.getLoginID() + " " + entry.getName());
        sendFile(BoxStatic.accessRightErrorJSP,req,resp);
        return;
      }
      session.setAttribute("filelib.CURFOLDER", String.valueOf(entry.getParent()));
      session.setAttribute("filelib.CURENTRY", null);

      home.deleteFolder(aBoxSession.getID(), entry);

      sendFile(folderContentJSP, req, resp);
      return;
    }
    sendError("No action defined", req, resp);
  }

  protected boolean saveFolder(HttpSession session, BoxSession aBoxSession,
  HttpServletRequest req, HttpServletResponse resp) throws Exception
  {
    FileLibEntry entry = (FileLibEntry) session.getAttribute("filelib.CURENTRY");
    if (entry == null)
    {
      sendFile(BoxStatic.errorJSP,req,resp);
      return false;
    }

    if (entry.getID()==-1)
    {
      FileLibEntry newEntry = home.add();
      entry.setId(newEntry.getID());
    }
    //XXTODO: Check duplicate name
    String tmp = req.getParameter("NAME");
    if ( tmp != null)
      entry.setName(tmp);
    if (entry.getFilename() == null || entry.getFilename().length() == 0)
      entry.setFilename(tmp);

    tmp = req.getParameter("DESCRIPTION");
    if ( tmp != null)
      entry.setDescription(tmp);
    entry.setLastmodifiedtime(new Timestamp(System.currentTimeMillis()));
    entry.setIsfolder(true);

    tmp = req.getParameter("READONLY");
    long curAttr = entry.getAttributes();
    if ( tmp != null )
    {
      if (tmp.compareTo("1") == 0)
        curAttr |= home.READONLY;
      else
        curAttr &= ~home.READONLY;
    }
    else
      curAttr &= ~home.READONLY;

    tmp = req.getParameter("INHERIT");
    if (tmp != null) {
      if (tmp.compareTo("1") == 0)
        curAttr |= home.INHERIT;
      else
        curAttr &= ~home.INHERIT;
    }
    else
      curAttr &= ~home.INHERIT;

    entry.setAttributes(curAttr);

    tmp = req.getParameter("TAKEOWNERSHIP");
    if ( tmp != null )
    {
      if (tmp.compareTo("1") == 0)
      {
        if (home.checkAccessRights(aBoxSession.getID(),entry, home.TAKEOWNERSHIP_ALLOW))
          entry.setOwnerid(aBoxSession.getID());
        else
        {
          logger.warn("Access rights violation for user " + aBoxSession.getLoginID() + " " + entry.getName());
          sendFile(BoxStatic.accessRightErrorJSP,req,resp);
          return false;
        }
      }
    }

    home.update(entry);
     //userID(?) + GroupFlag(1) + permissions(8)
    String[] permissions = req.getParameterValues("PERMISSIONS");
    home.updatePermissions(entry, permissions);

    session.setAttribute("filelib.CURFOLDER", String.valueOf(entry.getID()));
    return true;
  }

  public void setFolderEditJSP(String str)
  {
    folderEditJSP = str;
  }
  public void setFolderViewJSP(String str)
  {
    folderViewJSP = str;
  }
  public void setFolderContentJSP(String str)
  {
    folderContentJSP = str;
  }
  public void setFolderDeleteJSP(String str)
  {
    folderDeleteJSP = str;
  }

  /**
   * viewFolder
   *
   * @param entry FileLibEntry
   * @param session HttpSession
   * @param aBoxSession BoxSession
   * @param req HttpServletRequest
   * @param resp HttpServletResponse
   */
  protected void viewFolder(FileLibEntry entry, HttpSession session, BoxSession aBoxSession,
                            HttpServletRequest req, HttpServletResponse resp) throws Exception
  {
    if (!home.checkAccessRights(aBoxSession.getID(), entry, home.BROWSE_ALLOW))
    {
      logger.warn("Access rights violation for user " + aBoxSession.getLoginID() +
                  " " + entry.getName());
      sendFile(BoxStatic.accessRightErrorJSP, req, resp);
      return;
    }
    session.setAttribute("filelib.CURENTRY", entry);
    sendFile(folderViewJSP, req, resp);
  }

}
